<?php
/**
 * 切片上传
 */
namespace lico\Tool\Upload;

class Slice
{

    protected $config;
    protected $file;
    protected $ext;
    protected $error;

    public function __construct(&$config)
    {
        $this->config = &$config;
    }

    /**
     * 设置错误
     */
    protected function setError($error)
    {
        $this->error = $error;
        return false;
    }

    /**
     * 获取错误
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 文件检查
     */
    public function checkFile($file)
    {

        if (empty($this->config['sliceNum']) || empty($this->config['sliceTotal'])) {
            return $this->setError('切片上传参数异常');
        }

        if (empty($file) || $file['file']['error']) {
            return $this->setError('上传失败');
        }
        $this->file = $file['file'];

        if (!in_array($this->file['type'], $this->config['allowExt'])) {
            return $this->setError('文件格式不正确，当前格式：' . $this->file['type']);
        }

        if ($this->file['size'] > ($this->config['maxSize'] * $this->config['sliceTotal']) * 1024 * 1024) {
            return $this->setError('文件太大，请限制在' . $this->config['maxSize'] . '以内');
        }

        $this->ext = substr($this->file['type'], strpos($this->file['type'], '/') + 1);

        return true;
    }

    /**
     * 上传保存
     */
    public function save()
    {

        $folderPath = strtr(ROOT_PATH . $this->config['saveFolder'], '/', DS);
        if (!is_dir($folderPath)) {
            mkdir($folderPath, 0750, true);
        }

        $uploadEnd = $this->config['sliceNum'] >= $this->config['sliceTotal'];

        //临时目录
        if (!$this->config['sliceUid']) {
            $this->config['sliceUid'] = microtime(true);
            if (!is_dir($folderPath . DS . $this->config['sliceUid'])) {
                mkdir($folderPath . DS . $this->config['sliceUid'], 0750, true);
            }
        }
        $filename = $this->config['sliceUid'] . DS . $this->config['sliceNum'];

        $success = move_uploaded_file($this->file["tmp_name"], $folderPath . DS . $filename); //将临时地址移动到指定地址
        if (!$success || $uploadEnd) {
            //失败或者完成则删除文件夹极其所有子文件
            $hasFilesTmp = scandir($folderPath . DS . $this->config['sliceUid']);
            if ($hasFilesTmp) {
                foreach ($hasFilesTmp as $key => $value) {
                    if ($value != '.' || $value != '..') {
                        @unlink($folderPath . DS . $this->config['sliceUid'] . $value);
                    }
                }
                @rmdir($folderPath . DS . $this->config['sliceUid']);
            }
            return false;
        }

        //防止文件名重复
        mt_srand((float) microtime() * 1000000); //随机数播种
        $randnum = str_pad(mt_rand(10000000, 99999999), 6, '0', STR_PAD_LEFT);
        $realFileName = MD5(time() . $randnum) . '.' . $this->ext;

        //分片数据合并
        $blob = file_get_contents($folderPath . DS . $filename);
        file_put_contents($folderPath . DS . $realFileName, FILE_APPEND);

        return $realFileName;
    }

    /**
     * 获取分片唯一批次id
     */
    public function getSliceUid()
    {
        return $this->config['sliceUid'];
    }
}
